﻿using System.Linq;
using System.Web.Mvc;
using BLL.Enum;
using BLL.Installer;
using BLL.Interface.Apply;
using BLL.Interface.OperatingSystem;
using BLL.Model.Apply;
using BLL.Utility;
using WayCloud.ViewModel;
using WayCloud.ViewModel.Apply;

namespace WayCloud.Controllers.Apply
{
    [Authorize]
    public class ApplyController : Controller
    {
        [NonAction]
        private static string ConvertStatus(ApplyProcessStatus status)
        {
            switch (status)
            {
                case ApplyProcessStatus.Wait:
                    return "待审批";
                case ApplyProcessStatus.Pass:
                    return "审批通过";
                case ApplyProcessStatus.Refuse:
                    return "审批未通过";
                case ApplyProcessStatus.Save:
                    return "暂存";
                default:
                    return "";
            }
        }

        [NonAction]
        private bool InsertOrUpdateApply(ApplyInfo info)
        {
            info.ApplyUserId = this.GetLoginUser().UserInfo.Id;
            var applyInfoManager = ContainerHelper.Instance.Container.Resolve<IApplyInfo>();
            var result = info.Id == 0
                ? applyInfoManager.AddApplyInfo(info)
                : applyInfoManager.UpdateApplyInfo(info);
            return result;
        }

        [NonAction]
        private void CreateOSList()
        {
            var osInfoManager = ContainerHelper.Instance.Container.Resolve<IOperatingSystemInfo>();
            var osList = osInfoManager.GetAllOperatingSystemInfo();
            ViewBag.OSList =
                osList.Select(p => new { p.Id, Name = string.Format("{0}     |Version:{1}", p.Name, p.Version) });
        }

        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult List(ApplyCondition condition)
        {
            AnalyseJqGridQueryString ajqs = new AnalyseJqGridQueryString(Request.QueryString);
            var page = ajqs.GetPageInfo();
            var sort = ajqs.GetSortField();
            if (!User.IsInRole("admin"))
            {
                condition.ApplyUserAccount = this.GetLoginUser().UserAccountName;
            }
            var applyInfoManager = ContainerHelper.Instance.Container.Resolve<IApplyInfo>();
            var applyInfoList = applyInfoManager.GetApplyInfoByFilter(condition, sort, page);
            var result = applyInfoList.Select(p => new
            {
                p.ApplyDate,
                p.ApplyUser.UserName,
                p.CPUCore,
                p.Comment,
                Status = ConvertStatus(p.CurrentStatus),
                p.DiskSize,
                p.Id,
                p.MemroySize,
                p.Title
            }).ToList();

            var jqResult = new JqGrid(page, result);
            return Json(jqResult, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult FindApplyInfoById(string id)
        {
            CreateOSList();
            if (string.IsNullOrWhiteSpace(id))
            {
                return View("Add");
            }
            if (User.IsInRole("admin"))
            {
                var applyInfoManager = ContainerHelper.Instance.Container.Resolve<IApplyInfo>();
                var result = applyInfoManager.FindApplyInfoById(int.Parse(id));
                ViewBag.Status = ConvertStatus(result.CurrentStatus);
                ViewBag.Title = string.Format("审批申请：{0}", result.Title);
                return View("Approval", result);
            }
            return null;
        }

        [HttpGet]        
        public ActionResult Edit(int id)
        {
            CreateOSList();
            var applyInfoManager = ContainerHelper.Instance.Container.Resolve<IApplyInfo>();
            var result = applyInfoManager.FindApplyInfoById(id);
            if (result.ApplyUserId == this.GetLoginUser().UserInfoId)
            {
                return View("Add", result);
            }
            return null;
        }

        [HttpPost]
        public ActionResult Submit([Bind(Exclude = "ApplyUserId,OperatingSystemType")] ApplyInfo info)
        {
            if (!ModelState.IsValid)
            {
                return View("Add", info);
            }
            info.CurrentStatus = ApplyProcessStatus.Wait;
            return InsertOrUpdateApply(info) ? Content("ok") : Content("error");
        }

        [HttpPost]
        public ActionResult Save([Bind(Exclude = "ApplyUserId,OperatingSystemType")] ApplyInfo info)
        {
            if (!ModelState.IsValid)
            {
                return View("Add", info);
            }
            info.CurrentStatus = ApplyProcessStatus.Save;
            return InsertOrUpdateApply(info) ? Content("ok") : Content("error");
        }

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult ApprovalPass(int id, string approvalComment)
        {
            if (!ModelState.IsValid)
            {
                return Content("error");
            }
            var userId = this.GetLoginUser().UserInfoId;
            var applyInfoManager = ContainerHelper.Instance.Container.Resolve<IApplyInfo>();
            var result = applyInfoManager.ApprovalApply(id, approvalComment, userId, ApplyProcessStatus.Pass);
            return result ? Content("ok") : Content("出现错误，请重试！");
        }

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult ApprovalRefuse(int id, string approvalComment)
        {
            if (!ModelState.IsValid)
            {
                return Content("error");
            }
            var userId = this.GetLoginUser().UserInfoId;
            var applyInfoManager = ContainerHelper.Instance.Container.Resolve<IApplyInfo>();
            var result = applyInfoManager.ApprovalApply(id, approvalComment, userId, ApplyProcessStatus.Refuse);
            return result ? Content("ok") : Content("出现错误，请重试！");
        }

        [HttpGet]
        public ActionResult Details(int id)
        {
            var applyInfoManager = ContainerHelper.Instance.Container.Resolve<IApplyInfo>();
            var result = applyInfoManager.FindApplyInfoById(id);
            ViewBag.Status = ConvertStatus(result.CurrentStatus);
            if (User.IsInRole("admin"))
            {
                return View("Details", result);
            }
            if (result.ApplyUser.AccountName == User.Identity.Name)
            {
                return View("Details", result);
            }
            return null;
        }

    }
}